﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UFIDA.U8.YYNBJY.Operate
{
    public class Po_Pomain
    {
        public static string TBSO_SOmain(string filename, string dbname, string cvouchid, bool ilog, bool iilog)
        {
            PUBMethod.PMethod.printmsgs(filename, "======================[" + DateTime.Now.ToString() + "]采购订单方法START======================", true, ilog, iilog, System.Drawing.Color.Black);
            try
            {
                string condition = " and 1=1 ";
                if (!string.IsNullOrEmpty(cvouchid))
                {
                    condition += " and ccode='" + cvouchid + "'";
                }
                string DBcondition = " and 1=1 ";
                if (!string.IsNullOrEmpty(dbname))
                {
                    DBcondition += " and U8DBNAME='" + dbname + "' ";
                }
                string sql = "select Cvencode,Cuscode,U8DBNAME from EFYYNBJY..EF_U8CVENCONTROL where 1=1" + DBcondition;
                PUBMethod.PMethod.printmsgs(filename, "账套查询语句:" + sql, false, ilog, true, System.Drawing.Color.Red);
                DataTable dt = DBHelp.SQLHelper.GetDataTable(sql);
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        string U8DBNAME = dt.Rows[i]["U8DBNAME"].ToString();
                        string Cvencode = dt.Rows[i]["Cvencode"].ToString();
                        DataTable dtt = DBHelp.SQLHelper.GetDataTable("select Cuscode,U8DBNAME from EFYYNBJY..EF_U8CVENCONTROL where U8DBNAME<>'" + U8DBNAME + "'");
                        for (int j = 0; j < dtt.Rows.Count; j++)
                        {
                            string U8DBNAMES = dtt.Rows[j]["U8DBNAME"].ToString();
                            string Cuscode = dtt.Rows[j]["Cuscode"].ToString();
                            DBHelp.LogException.WriteiLog(filename, "TO[" + U8DBNAME + "]----FROM[" + U8DBNAMES + "]", ilog, iilog);
                            if (U8DBNAME == U8DBNAMES)
                            {
                                continue;
                            }
                            else
                            {
                                sql = "select * from " + U8DBNAMES + "..RdRecord01 where 1=1 and ddate>='2024-12-01' and isnull(cHandler,'')<>'' and cvencode='" + Cvencode + "' " + condition;
                                PUBMethod.PMethod.printmsgs(filename, "采购入库单查询语句:" + sql, false, ilog, true, System.Drawing.Color.Red);
                                DataTable dtd = DBHelp.SQLHelper.GetDataTable(sql);
                                if (dtd.Rows.Count > 0)
                                {
                                    for (int r = 0; r < dtd.Rows.Count; r++)
                                    {
                                        List<string> list = new List<string>();
                                        string cAcc_Id = U8DBNAMES.Substring(7, 3);
                                        string cAcc_IdS = U8DBNAME.Substring(7, 3);
                                        string ID = dtd.Rows[r]["ID"].ToString();//入库单ID
                                        string ccode = dtd.Rows[r]["ccode"].ToString();//入库单号
                                        PUBMethod.PMethod.printmsgs(filename, "TO[" + U8DBNAME + "]----FROM[" + U8DBNAMES + "]----入库单号[" + ccode + "]", true, ilog, true, System.Drawing.Color.Red);
                                        string ddate = dtd.Rows[r]["ddate"].ToString();//入库日期
                                        string cMemo = dtd.Rows[r]["cMemo"].ToString();//备注
                                        string cMaker = dtd.Rows[r]["cMaker"].ToString();
                                        string cverifier = dtd.Rows[r]["cHandler"].ToString();
                                        string cPersonCode = dtd.Rows[r]["cPersonCode"].ToString();
                                        if (!string.IsNullOrEmpty(cPersonCode))
                                        {
                                            //DBHelp.LogException.WriteiLog(filename, "人员编码校验", ilog, iilog);
                                            int rcw = Convert.ToInt32(DBHelp.SQLHelper.GetString("select count(*) from " + U8DBNAME + "..person where cPersonCode='" + cPersonCode + "' "));
                                            if (rcw == 0)
                                            {
                                                PUBMethod.PMethod.printmsgs(filename, "TO[" + U8DBNAME + "]----FROM[" + U8DBNAMES + "]--人员编码[" + cPersonCode + "]不存在!", true, ilog, true, System.Drawing.Color.Red);
                                                continue;
                                            }
                                        }
                                        string cwhcode = dtd.Rows[r]["cwhcode"].ToString();
                                        if (!string.IsNullOrEmpty(cwhcode))
                                        {
                                            //DBHelp.LogException.WriteiLog(filename, "仓库编码校验", ilog, iilog);
                                            int rcw = Convert.ToInt32(DBHelp.SQLHelper.GetString("select count(*) from " + U8DBNAME + "..Warehouse where cWhCode='" + cwhcode + "' "));
                                            if (rcw == 0)
                                            {
                                                PUBMethod.PMethod.printmsgs(filename, "TO[" + U8DBNAME + "]----FROM[" + U8DBNAMES + "]--仓库编码[" + cwhcode + "]不存在!", true, ilog, true, System.Drawing.Color.Red);
                                                continue;
                                            }
                                        }
                                        string crdcode = "201";
                                        //DBHelp.LogException.WriteiLog(filename,"1",ilog,iilog);
                                        DataTable dte = DBHelp.SQLHelper.GetDataTable("select * from  EFYYNBJY..EF_U8POTBLOG where POID='" + ID + "' and FU8DBNAME='" + U8DBNAMES + "' and TU8DBNAME='" + U8DBNAME + "' and TBLOG LIKE '%成功%'");
                                        if (dte.Rows.Count > 0)
                                        {
                                            PUBMethod.PMethod.printmsgs(filename, "TO[" + U8DBNAME + "]----FROM[" + U8DBNAMES + "]----入库单号[" + ccode + "]已同步!", true, ilog, true, System.Drawing.Color.Red);
                                            continue;
                                        }
                                        else
                                        {
                                            
                                            string cdeptcode = DBHelp.SQLHelper.GetString("select cdepcode from  " + U8DBNAME + "..Department where cDepName='商务部' ");
                                            string ccusoaddress = "", ccusname = "", ccusheadcode = "", ccusperson = "";
                                            DataTable dc = DBHelp.SQLHelper.GetDataTable("select ccusperson,ccusheadcode,ccusname,cCusOAddress from  " + U8DBNAME + "..customer where cCusCode='" + Cuscode + "' ");
                                            if (dc.Rows.Count > 0)
                                            {
                                                ccusoaddress = dc.Rows[0]["cCusOAddress"].ToString();
                                                ccusname = dc.Rows[0]["ccusname"].ToString();
                                                ccusheadcode = dc.Rows[0]["ccusheadcode"].ToString();
                                                ccusperson = dc.Rows[0]["ccusperson"].ToString();
                                            }
                                            //DBHelp.LogException.WriteiLog(filename, "2", ilog, iilog);
                                            #region 销售订单主表
                                            //主键流水
                                            int SID = 0, AutoID = 0;
                                            string sqlD = @"select iFatherId,iChildId from UFSystem..UA_Identity where cAcc_Id='" + cAcc_IdS + "' and cVouchType='Somain' ";
                                            DataTable dtId = DBHelp.SQLHelper.GetDataTable(sqlD);
                                            if (dtId.Rows.Count > 0)
                                            {
                                                SID = Convert.ToInt32(dtId.Rows[0]["iFatherId"]);
                                                AutoID = Convert.ToInt32(dtId.Rows[0]["iChildId"]);
                                            }
                                            else
                                            {
                                                SID = 1; AutoID = 1;
                                                if (DBHelp.SQLHelper.ExecuteSql("INSERT INTO [UFSystem].[dbo].[UA_Identity]([cAcc_Id],[cVouchType],[iFatherId],[iChildId])VALUES('" + cAcc_IdS + "', 'Somain', 1, 1)") > 1)
                                                {
                                                    PUBMethod.PMethod.printmsgs(filename, "订单ID执行失败!", true, ilog, true, System.Drawing.Color.Red);
                                                    continue;
                                                }
                                            }
                                            SID = SID + 1;
                                            string XSID = "1" + SID.ToString().PadLeft(9, '0');
                                            list.Add("update UFSystem..UA_Identity set iFatherId=iFatherId+1 where cAcc_Id='" + cAcc_IdS + "' and cVouchType='Somain'");
                                            PUBMethod.PMethod.printmsgs(filename, "XSID=["+XSID+"]", false, ilog, true, System.Drawing.Color.Red);
                                            string sdj = "";
                                            sdj = @"Insert Into " + U8DBNAME + @"..SO_SOMain(csysbarcode,ccrmpersoncode,ccrmpersonname,cmainpersoncode,ccurrentauditor,
                                                     id,ivtid,cchanger,cbustype,ccrechpname,
                                                     cstcode,outid,ddate,csocode,ccuscode,
                                                     cdepcode,cpersoncode,csccode,ccusoaddress,cpaycode,
                                                     cexch_name,iexchrate,itaxrate,imoney,cmemo,
                                                     istatus,cmaker,cverifier,ccloser,cdefine1,
                                                     cdefine2,cdefine3,cdefine5,cdefine7,cdefine8,
                                                     cdefine9,cdefine10,cdefine11,cdefine12,cdefine13,
                                                     cdefine14,cdefine15,cdefine16,dpredatebt,dpremodatebt,
                                                     bdisflag,clocker,ccusname,breturnflag,ccusperson,
                                                     coppcode,cmodifier,caddcode,ccuspersoncode,ccontactname,
                                                     cmobilephone,iflowid,cgatheringplan,iverifystate,ireturncount,
                                                     icreditstate,iswfcontrolled,cchangeverifier,bcashsale,cgathingcode,
                                                     iprintcount,bmustbook,fbookratio,fbooksum,fbooknatsum,
                                                     fgbooksum,fgbooknatsum,cinvoicecompany,contract_status,optnty_name,
                                                     ioppid,csvouchtype,cgcroutecode,csscode,cattachment,
                                                     cebtrnumber,cebbuyer,cebbuyernote,cebprovince,cebcity,
                                                     cebdistrict,cinvoicecusname,dverifydate,dverifysystime,cbcode)
                                                     Values (N'||SA17|(" + cAcc_Id + @")" + ccode + @"',Null,Null,Null,Null,
                                                     " + XSID + @",95,Null,N'普通销售',NULL,
                                                     N'01',Null,'" + ddate + @"',N'(" + cAcc_Id + @")" + ccode + @"',N'" + Cuscode + @"',
                                                     N'" + cdeptcode + @"'," + PUBMethod.PMethod.setvalue(2, cPersonCode) + @",Null," + PUBMethod.PMethod.setvalue(2, ccusoaddress) + @",Null,
                                                     N'人民币',1,Null,Null," + PUBMethod.PMethod.setvalue(2, cMemo) + @",
                                                     1,N'" + cMaker + @"','" + cverifier + @"',Null,Null,
                                                     Null,Null,Null,Null,Null,
                                                     Null,Null,Null,Null,Null,
                                                     Null,Null,Null,'" + ddate + @"','" + ddate + @"',
                                                     0,Null," + PUBMethod.PMethod.setvalue(2, ccusname) + @",0,Null,
                                                     Null,Null,Null,Null,Null,
                                                     Null,Null,Null,0,Null,
                                                     Null,0,Null,0,Null,
                                                     Null,0,Null,0,0,
                                                     Null,Null," + PUBMethod.PMethod.setvalue(2, ccusheadcode) + @",1,Null,
                                                     Null,Null,Null,Null,Null,
                                                     Null,Null,Null,Null,Null,
                                                     Null,Null,'" + ddate + "','"+ddate+"','01')";
                                            list.Add(sdj); 
                                            #endregion
                                            #region 销售发货单
                                            //主键流水
                                            int FID = 0, FAutoID = 0;
                                            sqlD = @"select iFatherId,iChildId from UFSystem..UA_Identity where cAcc_Id='" + cAcc_IdS + "' and cVouchType='DISPATCH' ";
                                            dtId = DBHelp.SQLHelper.GetDataTable(sqlD);
                                            if (dtId.Rows.Count > 0)
                                            {
                                                FID = Convert.ToInt32(dtId.Rows[0]["iFatherId"]);
                                                FAutoID = Convert.ToInt32(dtId.Rows[0]["iChildId"]);
                                            }
                                            else
                                            {
                                                FID = 1; FAutoID = 1;
                                                if (DBHelp.SQLHelper.ExecuteSql("INSERT INTO [UFSystem].[dbo].[UA_Identity]([cAcc_Id],[cVouchType],[iFatherId],[iChildId])VALUES('" + cAcc_IdS + "', 'DISPATCH', 1, 1)") > 1)
                                                {
                                                    PUBMethod.PMethod.printmsgs(filename, "发货单ID执行失败!", true, ilog, true, System.Drawing.Color.Red);
                                                    continue;
                                                }
                                            }
                                            FID = FID + 1;
                                            string FHID = "1" + FID.ToString().PadLeft(9, '0');
                                            PUBMethod.PMethod.printmsgs(filename, "FHID=[" + FHID + "]", false, ilog, true, System.Drawing.Color.Red);
                                            list.Add("update UFSystem..UA_Identity set iFatherId=iFatherId+1 where cAcc_Id='" + cAcc_IdS + "' and cVouchType='DISPATCH'");

                                            sdj = " insert into  " + U8DBNAME + "..DispatchList(DLID,cDLCode,cVouchType,cSTCode,dDate,cDepCode,cPersonCode,cSOCode,cCusCode,cPayCode,cSCCode,cexch_name,iExchRate,iTaxRate,bFirst," +
                                                   " bReturnFlag,bSettleAll,cSaleOut,cVerifier,cMaker,iSale,cCusName,iVTid,cBusType,bIAFirst,bCredit,iverifystate,iswfcontrolled,bARFirst," +
                                                   " dverifydate,ccusperson,dcreatesystime,dverifysystime,iflowid,bsigncreate,bcashsale,bmustbook,bneedbill,baccswitchflag,ccuspersoncode ,cMemo,  " +
                                                   " cDefine10,cDefine3,cDefine12 ,cshipaddress,bsaleoutcreatebill,cinvoicecompany,csysbarcode,cbcode )" +
                                                   " values('" + FHID + "','(" + cAcc_Id + ")" + ccode + "','05','01','" + ddate + "', " +
                                                   " '" + cdeptcode + "'," + PUBMethod.PMethod.setvalue(2, cPersonCode) + "," +
                                                   " '(" + cAcc_Id + ")" + ccode + "',  '" + Cuscode + "',  null,  null, " +
                                                   " '人民币','1','13', 0,'0',0,'(" + cAcc_Id + ")" + ccode + "','" + cMaker + "','" + cMaker + "', " +
                                                   " 0,'" + ccusname + "','71','分期收款',0,0,0,0,0, " +
                                                   " '" + ddate + "'," + PUBMethod.PMethod.setvalue(2, ccusperson) + ",getdate(),getdate(),0,0,0,0,1,0, " +
                                                   " " + PUBMethod.PMethod.setvalue(2, ccusperson) + "," + PUBMethod.PMethod.setvalue(2, cMemo) + ", " +
                                                   " NULL ,NULL,NULL," + PUBMethod.PMethod.setvalue(2, ccusoaddress) + ",0 ," + PUBMethod.PMethod.setvalue(2, ccusheadcode) + ",'||SA01|" + ccode + "','01' )";
                                            list.Add(sdj);

                                            #endregion
                                            #region 销售出库单
                                            //主键流水
                                            int RID = 0, RAutoID = 0;
                                            sqlD = @"select iFatherId,iChildId from UFSystem..UA_Identity where cAcc_Id='" + cAcc_IdS + "' and cVouchType='rd' ";
                                            dtId = DBHelp.SQLHelper.GetDataTable(sqlD);
                                            if (dtId.Rows.Count > 0)
                                            {
                                                RID = Convert.ToInt32(dtId.Rows[0]["iFatherId"]);
                                                RAutoID = Convert.ToInt32(dtId.Rows[0]["iChildId"]);
                                            }
                                            else
                                            {
                                                RID = 1; RAutoID = 1;
                                                if (DBHelp.SQLHelper.ExecuteSql("INSERT INTO [UFSystem].[dbo].[UA_Identity]([cAcc_Id],[cVouchType],[iFatherId],[iChildId])VALUES('" + cAcc_IdS + "', 'rd', 1, 1)") > 1)
                                                {
                                                    PUBMethod.PMethod.printmsgs(filename, "发货单ID执行失败!", true, ilog, true, System.Drawing.Color.Red);
                                                    continue;
                                                }
                                            }
                                            RID = RID + 1;
                                            string RDID = "1" + RID.ToString().PadLeft(9, '0');
                                            PUBMethod.PMethod.printmsgs(filename, "RDID=[" + RDID + "]", false, ilog, true, System.Drawing.Color.Red);
                                            list.Add("update UFSystem..UA_Identity set iFatherId=iFatherId+1 where cAcc_Id='" + cAcc_IdS + "' and cVouchType='rd'");

                                            sdj = "insert into " + U8DBNAME + "..rdrecord32" +
                                                 " (id,brdflag,cvouchtype,cbustype,csource " +
                                                 "  ,cbuscode,cwhcode,ddate,ccode,crdcode " +
                                                 "  ,cdepcode,cpersoncode,cstcode,ccuscode,cdlcode " +
                                                 "  ,cmaker,vt_id,iswfcontrolled,dnmaketime " +
                                                 "  ,dnmodifytime,iprintcount,dVeriDate ,cHandler ,dnverifytime ,cMemo, " +
                                                 " cDefine10,cDefine12,cshipaddress,cinvoicecompany,csysbarcode) " +
                                                 "  values ( " +
                                                 "  '" + RDID + "',N'0',N'32','分期收款',N'发货单' " +
                                                 "  ,N'(" + cAcc_Id + ")" + ccode + "',N'" + cwhcode + "',N'" + ddate + "',N'(" + cAcc_Id + ")" + ccode + "'," + PUBMethod.PMethod.setvalue(2, crdcode) + " " +
                                                 "  ,'" + cdeptcode + "'," + PUBMethod.PMethod.setvalue(2, cPersonCode) + ",N'01', " +
                                                 " N'" + Cuscode + "',N'" + FHID + "' " +
                                                 "  ,'" + cMaker + "','87',0,'" + ddate + "' " +
                                                 "  , Null  ,0,'" + ddate + "','" + cMaker + "',getdate()," + PUBMethod.PMethod.setvalue(2, cMemo) + ", " +
                                                 " NULL,NULL," + PUBMethod.PMethod.setvalue(2, ccusoaddress) + "," + PUBMethod.PMethod.setvalue(2, ccusheadcode) + ",'||st32|(" + cAcc_Id + ")" + ccode + "')";
                                            list.Add(sdj);

                                            #endregion
                                            int rerr = 0;
                                            string sqls = "select * from " + U8DBNAMES + "..RdRecords01 where ID='" + ID + "' ";
                                            PUBMethod.PMethod.printmsgs(filename, "采购入库单子表查询语句:" + sqls, false, ilog, true, System.Drawing.Color.Red);
                                            DataTable dts = DBHelp.SQLHelper.GetDataTable(sqls);
                                            if (dts.Rows.Count > 0)
                                            {
                                                DBHelp.SQLHelper.ExecuteSql("delete from EFYYNBJY..EF_U8POTBLOG where POID='" + ID + "' AND POID='" + ID + "' and FU8DBNAME='" + U8DBNAMES + "' and TU8DBNAME='" + U8DBNAME + "'");
                                                
                                                for (int s = 0; s < dts.Rows.Count; s++)
                                                {
                                                    string RDAutoid = dts.Rows[s]["Autoid"].ToString();

                                                    AutoID = AutoID + 1;
                                                    string XSIDS = "1" + AutoID.ToString().PadLeft(9, '0');
                                                    string cinvcode = dts.Rows[s]["cinvcode"].ToString();
                                                    string cinvname = DBHelp.SQLHelper.GetString("select cinvname from " + U8DBNAME + @"..Inventory where cinvcode='" + cinvcode + "'");
                                                    string iquantity = dts.Rows[s]["iquantity"].ToString();
                                                    string dbarvdate = dts.Rows[s]["dMadeDate"].ToString();
                                                    string dMadeDate = dts.Rows[s]["dMadeDate"].ToString();//生产日期
                                                    string dVDate = dts.Rows[s]["dVDate"].ToString();//失效日期
                                                    string cBatch = dts.Rows[s]["cbatch"].ToString();
                                                    string iMassDate = dts.Rows[s]["iMassDate"].ToString();
                                                    string errmsg = "";
                                                    string where = " and 1=1 ";
                                                    if (!string.IsNullOrEmpty(cBatch))
                                                    {
                                                        where += " and cbatch='" + cBatch + "' ";
                                                    }
                                                    //校验现存量
                                                    sql = "select count(1) from " + U8DBNAME + "..CurrentStock " +
                                                        " where cwhcode='" + cwhcode + "' and cinvcode='" + cinvcode + "' and iquantity >= " + iquantity + " " + where + " ";
                                                    int co = PUBMethod.PMethod.ToInt(DBHelp.SQLHelper.GetString(sql));
                                                    if (co == 0)
                                                    {
                                                        if (!string.IsNullOrEmpty(where))
                                                        {
                                                            errmsg += " 批号[" + cBatch + "] ";
                                                        }
                                                        errmsg += "存货编码[" + cinvcode + "]  数量不足[" + iquantity + "] ";
                                                        DBHelp.SQLHelper.ExecuteSql("insert into EFYYNBJY..EF_U8POTBLOG(POCODE,POID,SOCODE,SOID,FU8DBNAME,TU8DBNAME,TBDATE,TBLOG) values ('" + ccode + "','" + ID + "','(" + cAcc_Id + ")" + ccode + "','" + XSID + "','" + U8DBNAMES + "','" + U8DBNAME + "',GETDATE(),'" + errmsg + "')");
                                                        PUBMethod.PMethod.printmsgs(filename, errmsg, true, ilog, true, System.Drawing.Color.Red);
                                                        rerr++;
                                                        list.Clear();
                                                        break;
                                                    }
                                                    decimal itaxprice = Convert.ToDecimal(dts.Rows[s]["iTaxPrice"].ToString()),
                                                        iunitprice = Convert.ToDecimal(dts.Rows[s]["iUnitCost"].ToString()),
                                                        iMoney = Convert.ToDecimal(dts.Rows[s]["iPrice"].ToString()),
                                                        itax = Convert.ToDecimal(dts.Rows[s]["iTaxPrice"].ToString()),
                                                        itaxrate = Convert.ToDecimal(dts.Rows[s]["iTaxRate"].ToString()),
                                                        isum = Convert.ToDecimal(dts.Rows[s]["isum"].ToString()),
                                                        itaxunitprice = Convert.ToDecimal(dts.Rows[s]["iOriTaxCost"].ToString());
                                                    decimal bbdj = iunitprice, bbje = iMoney, bbse = itax, bbsum = isum;//本币

                                                    sdj = @"Insert Into " + U8DBNAME + @"..SO_SODetails(cinvcode,dpredate,iquantity,inum,iquotedprice,
                                                             iunitprice,itaxunitprice,imoney,itax,isum,
                                                             idiscount,inatunitprice,inatmoney,inattax,inatsum,
                                                             inatdiscount,ifhnum,ifhquantity,ifhmoney,ikpquantity,
                                                             ikpnum,ikpmoney,cmemo,cfree1,cfree2,
                                                             isosid,kl,kl2,cinvname,itaxrate,
                                                             cdefine22,cdefine23,cdefine24,cdefine25,cdefine26,
                                                             cdefine27,citemcode,citem_class,citemname,citem_cname,
                                                             cfree3,cfree4,cfree5,cfree6,cfree7,
                                                             cfree8,cfree9,cfree10,iinvexchrate,cunitid,
                                                             id,cdefine28,cdefine29,cdefine30,cdefine31,
                                                             cdefine32,cdefine33,cdefine34,cdefine35,fpurquan,
                                                             fsalecost,fsaleprice,cquocode,iquoid,cscloser,
                                                             dpremodate,irowno,icusbomid,imoquantity,ccontractid,
                                                             ccontracttagcode,ccontractrowguid,ippartseqid,ippartid,ippartqty,
                                                             ccusinvcode,ccusinvname,iprekeepquantity,iprekeepnum,iprekeeptotquantity,
                                                             iprekeeptotnum,fcusminprice,fimquantity,fomquantity,ballpurchase,
                                                             finquantity,foutquantity,iexchsum,imoneysum,iaoids,
                                                             cpreordercode,fretquantity,fretnum,borderbom,borderbomover,
                                                             idemandtype,cdemandcode,cdemandmemo,iimid,ccorvouchtype,
                                                             icorrowno,busecusbom,body_outid,bsaleprice,bgift,
                                                             forecastdid,cdetailsdemandcode,cdetailsdemandmemo,cbsysbarcode,fappqty,
                                                             cparentcode,cchildcode,fchildqty,fchildrate,icalctype,
                                                             icurpartid,cfactorycode,gcsourceid,gcsourceids)
                                                             values('" + cinvcode + @"','" + dbarvdate + @"','" + iquantity + @"',Null,0,
                                                             " + iunitprice + @"," + itaxunitprice + @"," + iMoney + @"," + itax + @"," + isum + @",
                                                             0," + iunitprice + @"," + iMoney + @"," + itax + @"," + isum + @",
                                                             0,Null,Null,Null,Null,
                                                             Null,Null,Null,Null,Null,
                                                             " + XSIDS + @",100,100,N'" + cinvname + @"',6,
                                                             Null,Null,Null,Null,Null,
                                                             Null,Null,Null,Null,Null,
                                                             Null,Null,Null,Null,Null,
                                                             Null,Null,Null,Null,Null,
                                                             " + XSID + @",Null,Null,Null,Null,
                                                             Null,Null,Null,Null,Null,
                                                             0,0,Null,Null,Null,
                                                             '" + ddate + @"'," + (s + 1) + @",Null,Null,Null,
                                                             Null,Null,Null,Null,Null,
                                                             Null,Null,Null,Null,Null,
                                                             Null,0,Null,Null,0,
                                                             Null,Null,Null,Null,Null,
                                                             Null,Null,Null,0,0,
                                                             Null,Null,Null,Null,Null,
                                                             Null,0,Null,1,0,
                                                             Null,Null,Null,N'||SA17|(" + cAcc_Id + @")" + ccode + @"|" + (s + 1) + @"',Null,
                                                             Null,Null,Null,Null,Null,
                                                             Null,Null,Null,Null)";
                                                    list.Add(sdj);
                                                    //发货单
                                                    FAutoID = FAutoID + 1;
                                                    string FHIDS = "1" + FAutoID.ToString().PadLeft(9, '0');
                                                    sdj = "";
                                                    string cAssUnit = "", iinvexchrate = "";
                                                    string sqlunit = "select  cSTComUnitCode,isnull(iChangRate,NULL) iChangRate   from " + U8DBNAME + "..inventory i " +
                                                        " left join " + U8DBNAME + "..ComputationUnit c  on i.cSTComUnitCode=c.cComunitCode  where cinvcode='" + cinvcode + "'";
                                                    DataTable dtiv = DBHelp.SQLHelper.GetDataTable(sqlunit);
                                                    if (dtiv.Rows.Count > 0)
                                                    {
                                                        cAssUnit = "'" + dtiv.Rows[0]["cSTComUnitCode"].ToString() + "'";
                                                        if (!string.IsNullOrEmpty(dtiv.Rows[0]["iChangRate"].ToString()))
                                                        {
                                                            iinvexchrate = "" + dtiv.Rows[0]["iChangRate"].ToString() + "";
                                                        }
                                                        else
                                                        {
                                                            iinvexchrate = "NULL";
                                                        }
                                                    }
                                                    else
                                                    {
                                                        cAssUnit = "NULL";
                                                        iinvexchrate = "NULL";
                                                    }

                                                    sdj = " insert into " + U8DBNAME + "..DispatchLists(iDLsID,DLID,iCorID,cWhCode,cInvCode,iQuantity,iNum," +
                                                             " iQuotedPrice,iUnitPrice,iTaxUnitPrice,imoney,iTax," +
                                                             " iSum,iDisCount,iNatUnitPrice," +
                                                             " iNatMoney,iNatTax,iNatSum,iNatDisCount,iSettleNum,iSettleQuantity,bSettleAll,iTB,TBQuantity,iSOsID,KL,KL2,cInvName,iTaxRate," +
                                                             "  fOutQuantity,fOutNum,fSaleCost,fSalePrice,bIsSTQc,iInvExchRate,cUnitID,fEnSettleQuan,fEnSettleSum,bGsp,cSoCode,cMassUnit," +
                                                             "  bQANeedCheck,bQAUrgency,bQAChecking,bQAChecked,fsumsignquantity,fsumsignnum,bcosting,cordercode,iorderrowno,fcusminprice,irowno," +
                                                             "  iExpiratDateCalcu,idemandtype,cdemandcode,cdemandid,idemandseq,bneedsign ,bIACreateBill,bsaleprice,cBatch,cbsysbarcode,cPosition,cDefine32 ,cdefine22,cDefine33,cDefine36,cItem_class,cItem_CName,cItemCode,cItemName )" +
                                                             " values ('" + FHIDS + "','" + FHID + "','0','" + cwhcode + "','" + cinvcode + "','" + iquantity + "',null ," +
                                                             " '" + itaxprice + "','" + iunitprice + "','" + itaxprice + "','" + iMoney + "','" + itax + "', " +
                                                             " '" + isum + "','0','" + bbdj + "','" + bbje + "','" + bbse + "','" + bbsum + "', " +
                                                             " '0','0','0','0','0','0','" + XSIDS + "','100','100','" + cinvname + "','" + itaxrate + "', " +
                                                             " '" + iquantity + "','0','0','0','0'," + iinvexchrate + " ,null  , " +
                                                             " '0','0','0','(" + cAcc_Id + ")" + ccode + "','0'," +
                                                             " '0','0','0','0','0','0','1','(" + cAcc_Id + ")" + ccode + "','" + (s + 1) + "','0', " +
                                                             " '" + (s + 1) + "','0','1',null,null,null,'0',0,1," + PUBMethod.PMethod.setvalue(2, cBatch) + ",'||SA01|(" + cAcc_Id + ")" + ccode + "|" + (s + 1) + "',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL)";
                                                    list.Add(sdj);

                                                    //销售出库单
                                                    RAutoID = RAutoID + 1;
                                                    string RDIDS = "1" + RAutoID.ToString().PadLeft(9, '0');

                                                    sdj = "insert into " + U8DBNAME + "..rdrecords32 (autoid,id,cinvcode,iNum ,iquantity,iFlag,iDLsID " +
                                                            " ,iNQuantity,bLPUseFree,iRSRowNO,iOriTrackID,bCosting " +
                                                            " ,bVMIUsed,cbdlcode,iExpiratDateCalcu,iorderdid " +
                                                            " ,iordertype,iordercode,iorderseq,ipesodid,ipesotype " +
                                                            " ,cpesocode,ipesoseq,isotype,irowno " +
                                                            " ,cbsysbarcode,bIAcreatebill,bsaleoutcreatebill,bneedbill,iposflag,isodid,csocode," +
                                                            " isoseq,cBatch,iinvexchrate ,cPosition,cAssUnit ,cItem_class,cItemCName,cItemCode,cName,iUnitCost,iPrice,dMadeDate,dVDate,iMassDate  ) " +
                                                            " Values " +
                                                            "  ('" + RDIDS + "','" + RDID + "','" + cinvcode + "',null,'" + iquantity + "',0,'" + FHIDS + "' " +
                                                            "  ,'" + iquantity + "',0,0,0,1 " +
                                                            "  ,0,'(" + cAcc_Id + ")" + ccode + "',0,'" + XSIDS + "' " +
                                                            "  ,1,'(" + cAcc_Id + ")" + ccode + "','" + (s + 1) + "',null,1 " +
                                                            "  ,1,null,0,'" + (s + 1) + "' " +
                                                            "  ,null,0,0,0,0,'" + XSIDS + "','(" + cAcc_Id + ")" + ccode + "', " +
                                                            " '" + (s + 1) + "'," + PUBMethod.PMethod.setvalue(2, cBatch) + "," + iinvexchrate + ",NULL," + cAssUnit + ",NULL,NULL,NULL,NULL,'" + iunitprice + "','" + iMoney + "','"+dMadeDate+"','"+dVDate+"',"+ PUBMethod.PMethod.setvalue(2, iMassDate) + ")";
                                                    list.Add(sdj);

                                                    string xlh = "select * from " + U8DBNAMES + "..ST_SNState where cInvCode = '"+cinvcode+"' and cBatch = '"+cBatch+"' and dmdate = '"+dMadeDate+"'";
                                                    DataTable dtxlh = DBHelp.SQLHelper.GetDataTable(xlh);
                                                    if (dtxlh.Rows.Count>0)
                                                    {
                                                        for (int l = 0; l < dtxlh.Rows.Count; l++)
                                                        {
                                                            string cInvSN = dtxlh.Rows[l]["cInvSN"].ToString();
                                                            string imassunit = dtxlh.Rows[l]["imassunit"].ToString();
                                                            string imassdate = dtxlh.Rows[l]["imassdate"].ToString();
                                                            sdj = @"insert into " + U8DBNAME +@"..ST_SNDetail_SaleOut(iVouchsID,iVouchID,iRowNO,cInvCode,cWhCode,iSNPreState,
                                                                    iSNOperateCount,cBatch,cInvSN,dmdate,
                                                                    dvdate,imassunit,imassdate,ipremassdate,cprewhcode,
                                                                    cpreBatch,predmdate,predvdate,preimassunit,csource,idlsid)
                                                                    values ('"+RDIDS+@"','" + RDID +@"','"+(l+1)+ @"','" + cinvcode + @"','" + cwhcode + @"',2,
                                                                    2," + PUBMethod.PMethod.setvalue(2,cBatch) + @",'" + cInvSN + @"','" + dMadeDate + @"',
                                                                    '" + dVDate + @"','" + imassunit + @"','" + imassdate + @"','" + imassdate + @"','" + cwhcode + @"',
                                                                    " + PUBMethod.PMethod.setvalue(2, cBatch) + @",'" + dMadeDate + @"','" + dVDate + @"','" + imassunit + @"','发货单','"+FHID+@"')";
                                                            list.Add(sdj);
                                                            sdj = @"update " + U8DBNAME + @"..ST_SNState set iSNState=9 where cInvCode='"+cinvcode+@"' and cBatch="+PUBMethod.PMethod.setvalue(2,cBatch)+@", and cInvSN='"+cInvSN+@"'";
                                                            list.Add(sdj);
                                                        }
                                                    }

                                                    //回写 领料数 
                                                    sdj = "update " + U8DBNAME + "..SO_SODetails set iFHQuantity=isnull(iFHQuantity,0)+" + iquantity + " , " +
                                                                               " foutquantity=isnull(foutquantity,0)+" + iquantity + "  where iSOsID='" + XSIDS + "'";
                                                    list.Add(sdj);


                                                    //新增记账表
                                                    list.Add(@"insert into " + U8DBNAME + "..IA_SA_UnAccountVouch(IDUN,IDSUN,cVouTypeUN,cBustypeUN ) " +
                                                        "   values('" + FHID + "','" + FHIDS + "','05','分期收款') ");
                                                    //更新子件ID
                                                    list.Add("update UFSystem..UA_Identity set iChildId=iChildId+1 where cAcc_Id='" + cAcc_IdS + "' and cVouchType='Somain' ");
                                                    list.Add("update UFSystem..UA_Identity set iChildId=iChildId+1 where cAcc_Id='" + cAcc_IdS + "' and cVouchType='DISPATCH' ");
                                                    list.Add("update UFSystem..UA_Identity set iChildId=iChildId+1 where cAcc_Id='" + cAcc_IdS + "' and cVouchType='rd' ");
                                                }
                                                //更新库存 
                                                //sdj = "exec " + U8DBNAME + "..pro_uptcurrentStock '" + U8DBNAME + "','32','" + RDID + "'";
                                                sdj = "exec SP_ClearCurrentStock_ST";
                                                list.Add(sdj);
                                                
                                            }
                                            else
                                            {
                                                PUBMethod.PMethod.printmsgs(filename, "TO[" + U8DBNAME + "]----FROM[" + U8DBNAMES + "]采购入库单未查到明细行数据！", true, ilog, true, System.Drawing.Color.Red);
                                                continue;
                                            }
                                            if (rerr > 0)
                                            {
                                                list.Clear();
                                                continue;
                                            }
                                            else
                                            {
                                                int row = DBHelp.SQLHelper.ExecuteSqlTran(list);
                                                if (row > 0)
                                                {
                                                    PUBMethod.PMethod.printmsgs(filename, "[" + dbname + "]采购入库单同[" + U8DBNAME + "]成功==销售订单[(" + cAcc_Id + ")" + ccode + "]", true, ilog, true, System.Drawing.Color.Green);
                                                    string efs = "insert into EFYYNBJY..EF_U8POTBLOG(POCODE,POID,SOCODE,SOID,FU8DBNAME,TU8DBNAME,TBDATE,TBLOG) values ('" + ccode + "','" + ID + "','(" + cAcc_Id + ")" + ccode + "','" + XSID + "','" + U8DBNAMES + "','" + U8DBNAME + "',GETDATE(),'成功')";
                                                    DBHelp.SQLHelper.ExecuteSql(efs);
                                                }
                                                else
                                                {
                                                    PUBMethod.PMethod.printmsgs(filename, "[" + dbname + "]采购入库单同步[" + U8DBNAME + "]失败！！", true, ilog, true, System.Drawing.Color.Red);
                                                    string efs = "insert into EFYYNBJY..EF_U8POTBLOG(POCODE,POID,SOCODE,SOID,FU8DBNAME,TU8DBNAME,TBDATE,TBLOG) values ('" + ccode + "','" + ID + "','(" + cAcc_Id + ")" + ccode + "','" + XSID + "','" + U8DBNAMES + "','" + U8DBNAME + "',GETDATE(),'失败')";
                                                    DBHelp.SQLHelper.ExecuteSql(efs);
                                                }
                                            }
                                        }
                                    }

                                }
                                else
                                {
                                    PUBMethod.PMethod.printmsgs(filename, "TO[" + U8DBNAME + "]----FROM[" + U8DBNAMES + "]未查到采购入库单", true, ilog, true, System.Drawing.Color.Red);
                                }
                            }
                        }

                    }
                }
                else
                {
                    PUBMethod.PMethod.printmsgs(filename, "账套查询失败!", true, ilog, true, System.Drawing.Color.Red);
                }

            }
            catch (Exception ex)
            {
                PUBMethod.PMethod.printmsgs(filename, "采购订单同步异常:" + ex.Message, true, ilog, true, System.Drawing.Color.Red);
            }
            PUBMethod.PMethod.printmsgs(filename, "======================[" + DateTime.Now.ToString() + "]采购订单方法E N D======================", true, ilog, iilog, System.Drawing.Color.Black);
            return "结束";
        }
    }
}
